#openai初始化
import openai
from . import encoder
#返回一句话的token数量
def getToken(text):
    enc = encoder.get_encoder()
    return len(enc.encode(text))
#返回对话的总token
def getTokens(promptWords):
    sum = 0
    for i in promptWords:
        sum = sum + getToken(i['content'])
    return sum
#寻找从上到下最近的system位置
def findSystem(promptWords):
    sum = 0
    for i in promptWords:
        if i["role"] == "system":
            return sum
        else:
            sum = sum + 1
#删除从上到下最近的system
def delSystem(promptWords):
    del promptWords[findSystem(promptWords)]
#控制台打印某个对话所有消息
def printPromptWords(promptWords):
    for i in promptWords:
        print("role:{}  content:{}\n".format(i['role'],i['content']))
#删除所有非system消息
def delMessages(promptWords):
    textPositions = []
    for i in range(0,len(promptWords)):
        if promptWords[i]['role'] == 'system':
            continue
        else:
            textPositions.append(i)
    for i in textPositions[::-1]:
        del promptWords[i]
    #printPromptWords(n)
#聊天接口，n表示指定对话线程
def AIchat(promptWords,msg,temperature = 1,frequency_penalty = 0.5,presence_penalty = 0.5,logit_bias = {}):
    #特殊功能识别
    #tokens超长判断
    while getTokens(promptWords) >= 4000:
        print("limited length")
        if promptWords[0]['role'] == 'system':
            del promptWords[1]
            del promptWords[1]
        else:
            del promptWords[0]
            del promptWords[0]
    #system置底
    sysPosition = findSystem(promptWords)
    print("system position = {}".format(sysPosition))
    if len(promptWords) - sysPosition >= 4:
        print("sys changed")
        temp = promptWords[sysPosition]['content']
        delSystem(promptWords)
        promptWords.insert(-4, {"role": "system", "content": temp})
        temp = 0
        #printPromptWords(n)
    #创建请求
    promptWords.append({"role": "user", "content":msg})
    print("linking to openai.com")
    res=openai.ChatCompletion.create(
    model="gpt-3.5-turbo",
    messages=promptWords,
    temperature=temperature,
    frequency_penalty=frequency_penalty,
    presence_penalty=presence_penalty,
    logit_bias = logit_bias
    )
    #请求处理
    print("linked to openai.com")
    if res['choices'][0]['finish_reason'] == "stop":
        
        promptWords.append(res['choices'][0]['message'])
        
        return res['choices'][0]['message']['content']
    elif res['choices'][0]['finish_reason'] == "content_filter":
        return "这是碰都不能碰的滑梯！快闭嘴"
    elif res['choices'][0]['finish_reason'] == "length":
        del (promptWords)[1]
        del (promptWords)[1]
        promptWords.pop()
        return AIchat(promptWords,msg) 
    elif res['choices'][0]['finish_reason'] == "null":
        pass
    else:
        return "unexpected error occured"


